const Router = require('koa-router');
const userService = require('../services/userService');
const { authenticateToken, authorize } = require('../middlewares/auth.middleware');

const router = new Router();

/**
 * 用户相关路由
 */

// 获取当前用户信息
router.get('/me', authenticateToken, async (ctx) => {
  try {
    const userId = ctx.state.userId;
    const user = await userService.getUserById(userId);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: user
    };
  } catch (error) {
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 更新用户信息
router.put('/me', authenticateToken, async (ctx) => {
  try {
    const userId = ctx.state.userId;
    const updateData = ctx.request.body;
    
    // 不允许直接修改密码，密码修改有单独的接口
    if (updateData.password) {
      delete updateData.password;
    }
    
    const updatedUser = await userService.updateUser(userId, updateData);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: '用户信息更新成功',
      data: updatedUser
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 修改密码
router.put('/me/password', authenticateToken, async (ctx) => {
  // 密码修改功能本身逻辑正确，不需要修改中间件调用
  // 修改密码是用户自己的操作，只需要认证身份即可，不需要管理员权限
  try {
    const userId = ctx.state.userId;
    const { currentPassword, newPassword } = ctx.request.body;
    
    await userService.changePassword(userId, currentPassword, newPassword);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: '密码修改成功'
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 获取用户列表（管理员）
router.get('/', authenticateToken, authorize(['admin']), async (ctx) => {
  try {
    const { page = 1, limit = 10, search, role, status } = ctx.query;
    
    const filters = {};
    if (search) filters.search = search;
    if (role) filters.role = role;
    if (status) filters.status = status;
    
    const result = await userService.getUsers(filters, parseInt(page), parseInt(limit));
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: result.users,
      pagination: result.pagination
    };
  } catch (error) {
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 获取用户详情（管理员）
router.get('/:userId', authenticateToken, authorize(['admin']), async (ctx) => {
  try {
    const userId = ctx.params.userId;
    const user = await userService.getUserById(userId);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: user
    };
  } catch (error) {
    ctx.status = error.status || 404;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 更新用户信息（管理员）
router.put('/:userId', authenticateToken, authorize(['admin']), async (ctx) => {
  try {
    const userId = ctx.params.userId;
    const updateData = ctx.request.body;
    
    const updatedUser = await userService.updateUser(userId, updateData);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: '用户信息更新成功',
      data: updatedUser
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 删除用户（管理员）
router.delete('/:userId', authenticateToken, authorize(['admin']), async (ctx) => {
  try {
    const userId = ctx.params.userId;
    
    // 不允许删除当前登录用户
    if (userId === ctx.state.userId.toString()) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '不能删除当前登录的用户'
      };
      return;
    }
    
    await userService.deleteUser(userId);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: '用户删除成功'
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 禁用/启用用户（管理员）
router.put('/:userId/status', authenticateToken, authorize(['admin']), async (ctx) => {
  try {
    const userId = ctx.params.userId;
    const { status } = ctx.request.body;
    
    // 不允许修改当前登录用户的状态
    if (userId === ctx.state.userId.toString()) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '不能修改当前登录用户的状态'
      };
      return;
    }
    
    const updatedUser = await userService.updateUserStatus(userId, status);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: `用户${status === 'active' ? '启用' : '禁用'}成功`,
      data: updatedUser
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 获取用户统计信息
router.get('/stats/overview', authenticateToken, authorize(['admin']), async (ctx) => {
  try {
    const stats = await userService.getUserStats();
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: stats
    };
  } catch (error) {
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

module.exports = router;